package com.example.datamanage.exception;

import cn.hutool.core.util.StrUtil;
import com.example.datamanage.common.CodeEnum;
import com.example.datamanage.common.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.sql.SQLSyntaxErrorException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 28142
 * @description 全局异常处理器
 * @date 2023/7/24 17:20
 */
@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(MyException.class)
    @ResponseBody
    public Result handler(MyException e) {
        return Result.error(e.getCode(), e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handler2(MethodArgumentNotValidException e) {
        return Result.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Result handler3(ConstraintViolationException  e) {
        List<String> msgList = new ArrayList<>();
        for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
            msgList.add(constraintViolation.getMessage());
        }
        String msg = StrUtil.join(";", msgList.toArray());
        return Result.error(msg);
    }

    /* @ExceptionHandler(SQLSyntaxErrorException.class)
    @ResponseBody
    public Result handler4(SQLSyntaxErrorException e) {
        System.out.println("*********************");
        System.out.println(e);
        System.out.println(e.getMessage());
        return Result.error(CodeEnum.CODE_502.getCode(), e.getMessage());
    } */
}
